<template>
	<view class="content-box">
		<!-- 头部navbar -->
		<navbar :fixed="true" :bgColor="'#fff'" :leftIcon="true"></navbar>
		<view class="content">
			<view class="title">{{t('info.yzxx')}}</view>
			<view class="tip-box">
				<text class="tip-left">{{t('info.qsrfsd')}}</text> {{newEmail}}{{t('info.yxdyzm')}}：
				<text class="time">{{formatSeconds(time2)}}</text>
			</view>
			<view class="input-box">
				<input type="number" id="input1" v-model="code1" maxlength="1" @input="handleInput(1, $event)" @keydown="handleKeydown(1, $event)" />
				<input type="number" id="input2" v-model="code2" maxlength="1" @input="handleInput(2, $event)" @keydown="handleKeydown(2, $event)" />
				<input type="number" id="input3" v-model="code3" maxlength="1" @input="handleInput(3, $event)" @keydown="handleKeydown(3, $event)" />
				<input type="number" id="input4" v-model="code4" maxlength="1" @input="handleInput(4, $event)" @keydown="handleKeydown(4, $event)" />
				<input type="number" id="input5" v-model="code5" maxlength="1" @input="handleInput(5, $event)" @keydown="handleKeydown(5, $event)" />
				<input type="number" id="input6" v-model="code6" maxlength="1" @input="handleInput(6, $event)" @keydown="handleKeydown(6, $event)" />
			</view>
			<view class="no-received">
				{{t('info.mysd')}}
				<text v-if="time > 0" class="countdown">{{t('info.cxfs')}}（{{time}}s）</text>
				<text v-else @click="resendCode" class="resend-btn">{{t('info.cxfs')}}</text>
			</view>
		</view>
		<GlobalPopup ref="popup"></GlobalPopup>
	</view>
</template>

<script setup>
	import {
		useI18n
	} from 'vue-i18n';
	import {
		ref,
		computed,
		onMounted,
		nextTick
	} from 'vue';
	import { userApi, authApi } from '@/utils/api';
	const {
		t,
		locale
	} = useI18n();
	const code1 = ref('');
	const code2 = ref('');
	const code3 = ref('');
	const code4 = ref('');
	const code5 = ref('');
	const code6 = ref('');
	const newEmail = ref('');
	// const input1 = ref(null);
	// const input2 = ref(null);
	// const input3 = ref(null);
	// const input4 = ref(null);

	const handleInput = async (index, event) => {
		const value = event.detail.value;

		// 过滤非输入
		if (!value) {
			return;
		}
		if (index == 1) {
			// 跳转到下一个输入框
			uni.createSelectorQuery()
			    .select('#input2')
			    .node((res) => {
			      const input = res.node
			      input.focus()
			    })
			    .exec()
			
		} else if (index == 2) {
			// 跳转到下一个输入框
			uni.createSelectorQuery()
			    .select('#input3')
			    .node((res) => {
			      const input = res.node
			      input.focus()
			    })
			    .exec()
		} else if (index == 3) {
			// 跳转到下一个输入框
			uni.createSelectorQuery()
			    .select('#input4')
			    .node((res) => {
			      const input = res.node
			      input.focus()
			    })
			    .exec()
		} else if (index == 4) {
			// 跳转到下一个输入框
			uni.createSelectorQuery()
			    .select('#input5')
			    .node((res) => {
			      const input = res.node
			      input.focus()
			    })
			    .exec()
		} else if (index == 5) {
			// 跳转到下一个输入框
			uni.createSelectorQuery()
			    .select('#input6')
			    .node((res) => {
			      const input = res.node
			      input.focus()
			    })
			    .exec()
		} else if (index == 6) {
			//  获取完整验证码 提交
			inputFinally()
		}
	};

	// 处理键盘按下事件（主要处理删除键）
	const handleKeydown = (index, event) => {
		// 检查是否是删除键（Backspace）
		if (event.key === 'Backspace' || event.keyCode === 8) {
			// 如果当前输入框为空，则删除前一个输入框的内容并聚焦到前一个输入框
			const currentCode = getCurrentCode(index);
			if (!currentCode.value) {
				event.preventDefault(); // 阻止默认删除行为
				deletePreviousCode(index);
			}
		}
	};

	// 获取当前输入框的ref
	const getCurrentCode = (index) => {
		switch(index) {
			case 1: return code1;
			case 2: return code2;
			case 3: return code3;
			case 4: return code4;
			case 5: return code5;
			case 6: return code6;
			default: return code1;
		}
	};

	// 删除前一个输入框的内容并聚焦
	const deletePreviousCode = (currentIndex) => {
		if (currentIndex > 1) {
			const prevIndex = currentIndex - 1;
			const prevCode = getCurrentCode(prevIndex);
			prevCode.value = '';
			
			// 聚焦到前一个输入框
			uni.createSelectorQuery()
				.select(`#input${prevIndex}`)
				.node((res) => {
					const input = res.node;
					input.focus();
				})
				.exec();
		}
	};

	// 获取完整验证码
	const getFullCode = () => {
		return code1.value + code2.value + code3.value + code4.value + code5.value + code6.value;
	};

	const time = ref(60) //发送倒计时
	const time2 = ref(300) //验证码有效期
	let countdownTimer = null // 倒计时定时器
	let validityTimer = null // 有效期定时器
	onMounted(() => {
		// 接收页面参数
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const options = currentPage.options
		
		if (options.newEmail) {
			newEmail.value = decodeURIComponent(options.newEmail)
		}

		// 开始倒计时 5分钟
		validityTimer = setInterval(() => {
			if (time2.value > 0) {
				time2.value -= 1
			} else {
				time2.value = 0
				clearInterval(validityTimer)
			}
		}, 1000)

		starTime()
	});
	const formatSeconds = (seconds) => {
		const date = new Date(0);
		date.setSeconds(seconds); // 设置秒数
		return date.toISOString().substring(14, 19); // 提取 "MM:SS"
	}
	const starTime = () => {
		// 清除之前的定时器
		if (countdownTimer) {
			clearInterval(countdownTimer)
		}
		
		// 开始倒计时
		time.value = 60
		countdownTimer = setInterval(() => {
			if (time.value > 0) {
				time.value -= 1
			} else {
				time.value = 0
				clearInterval(countdownTimer)
				countdownTimer = null
			}
		}, 1000)
	}

	// 重新发送验证码
	const resendCode = async () => {
		try {
			// 调用发送验证码API
			const response = await authApi.sendMailCode({
				email: newEmail.value,
				type: 0 // 根据其他页面的实现，使用type: 0
			})

			uni.showToast({
				title: '验证码已重新发送',
				icon: 'success'
			})

			// 重新开始倒计时
			starTime()

		} catch (error) {
			uni.showToast({
				title: '发送失败，请稍后重试',
				icon: 'none'
			})
		}
	}

	const popup = ref()
	//输入框输入完成
	const inputFinally = async () => {
		const verificationCode = getFullCode()
		
		if (verificationCode.length !== 6) {
			uni.showToast({
				title: '请输入完整的验证码',
				icon: 'none'
			})
			return
		}

		try {
			// 调用更新邮箱API
			await userApi.updateEmail({
				code: verificationCode,
				email: newEmail.value
			})

			popup.value.open({
				title: t('my.xgcg'),
				content: '邮箱更新成功',
				loading: false,
			})

			// 延迟返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 2000)

		} catch (error) {
			uni.showToast({
				title: '验证码错误或已过期',
				icon: 'none'
			})
		}
	}
</script>

<style scoped lang="scss">
	.content-box {
		min-height: 100vh;
		background-color: #fff;
		// padding: 20rpx 30rpx 100rpx;
		box-sizing: border-box;
	}

	.content {
		padding: 55.82rpx 90.70rpx;

		.title {
			font-size: 48.84rpx;
			font-weight: 500;
			letter-spacing: 0rpx;
			line-height: 70.71rpx;
			color: rgba(18, 24, 38, 1);
			margin-bottom: 24.42rpx;
		}

		.tip-box {
			font-size: 27.91rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 40.42rpx;
			color: rgba(108, 114, 127, 1);
			margin-bottom: 24.42rpx;

			.tip-left {
				color: rgba(108, 114, 127, 1);
			}

			.time {
				color: rgba(2, 120, 220, 1);
			}
		}

		.input-box {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 20rpx;
			text-align: center;
			margin-bottom: 55.82rpx;

			input {
				width: 100rpx;
				height: 80rpx;
				opacity: 1;
				border-radius: 16rpx;
				background: rgba(249, 250, 251, 1);
				border: 2rpx solid rgba(229, 231, 235, 1);
				text-align: center;
				font-size: 32rpx;
				font-weight: 600;
				color: rgba(18, 24, 38, 1);
				transition: all 0.3s ease;
			}
			
			input:focus {
				border-color: rgba(2, 120, 220, 1);
				background: rgba(255, 255, 255, 1);
				box-shadow: 0 0 0 4rpx rgba(2, 120, 220, 0.1);
			}
		}

		.no-received {
			text-align: center;
			font-size: 24.42rpx;
			font-weight: 400;
			letter-spacing: 0rpx;
			line-height: 35.36rpx;
			color: rgba(18, 24, 38, 1);

			.countdown {
				color: rgba(2, 122, 218, 1);
			}

			.resend-btn {
				color: rgba(2, 122, 218, 1);
				cursor: pointer;
				text-decoration: underline;
				
				&:hover {
					color: rgba(1, 100, 180, 1);
				}
				
				&:active {
					color: rgba(1, 80, 160, 1);
				}
			}
		}
	}
</style>